package com.wzq.upms.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.wzq.permission.client.model.EasyUiTree;
import com.wzq.permission.client.model.MenuTypeEnum;
import com.wzq.permission.client.model.Pager;
import com.wzq.permission.client.model.admin.MenuModel;
import com.wzq.permission.client.model.admin.UserModel;
import com.wzq.permission.client.service.ApplicationService;
import com.wzq.permission.client.service.MenuService;
import com.wzq.permission.client.utils.TreeUtil;
import com.wzq.upms.annotation.Auth;
import com.wzq.upms.core.EasyUiData;
import com.wzq.upms.core.JsonResponse;
import com.wzq.upms.core.SessionUtils;

@Controller
@RequestMapping("menu")
public class MenuController {
	@Autowired
	private MenuService menuServiceClient;
	@Autowired
	private ApplicationService applicationServiceClient;
	/**
	 * 用户页面
	 */
	private static final String APPLICATION_VIEW = "menu/menu";
	
	@Value("${app.key}")
	private String appKey;
	
	/**
	 * 用户页面
	 * @param model 模型对象
	 * @param request request对象
	 * @return ModelAndView
	 * @throws Exception
	 */
	@RequestMapping("/list") 
	public ModelAndView  list(MenuModel model,HttpServletRequest request) throws Exception{
		ModelAndView mv = new ModelAndView(APPLICATION_VIEW);
		request.setAttribute("applicationId", model.getApplicationId());
		return mv;
	}
	
	/**
	 * 获取数据列表
	 * @param model 模型对象
	 * @param pager 分页对象
	 * @return EasyUiData
	 * @throws Exception
	 */
	@RequestMapping("/dataList") 
	@ResponseBody
	public EasyUiData<MenuModel> dataList(MenuModel model,Pager pager) throws Exception{
		EasyUiData<MenuModel> data = new EasyUiData<MenuModel>();
		List<MenuModel> result = new ArrayList<MenuModel>();
		int total =menuServiceClient.queryByCount(model);
		MenuModel parentMenu = menuServiceClient.queryById(model.getParentId());
		if(parentMenu!=null && model.getParentId()!=null && parentMenu.getApplicationId()==model.getApplicationId()){
			result.add(parentMenu);
			total += 1;
		}
		List<MenuModel> menuList = menuServiceClient.queryList(model, pager);
		result.addAll(menuList);
		data.setTotal(total);
		data.setRows(result==null?new ArrayList<MenuModel>():result);
		return data;
	}
	
	
	/**
	 * 添加或修改数据
	 * @param model 模型对象
	 * @throws Exception
	 */
	@RequestMapping("/add")
	@ResponseBody
	public JsonResponse add(MenuModel model,HttpServletRequest request) throws Exception{
		JsonResponse response = new JsonResponse(JsonResponse.SUCCESS,"保存成功");
		UserModel user = SessionUtils.getUser(request);
		model.setCreateUser(user.getUserName());
		model.setUpdateUser(user.getUserName());
		model.setChildrens(getReqOperateMenus(request,model.getApplicationId()));
		menuServiceClient.add(model);
		return response;
	}
	
	/**
	 * 添加或修改数据
	 * @param model 模型对象
	 * @throws Exception
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public JsonResponse edit(MenuModel model,HttpServletRequest request) throws Exception{
		JsonResponse response = new JsonResponse(JsonResponse.SUCCESS,"修改成功");
		UserModel user = SessionUtils.getUser(request);
		model.setUpdateTime(new Date());
		model.setCreateUser(user.getUserName());
		model.setUpdateUser(user.getUserName());
		model.setChildrens(getReqOperateMenus(request,model.getApplicationId()));
		menuServiceClient.updateBySelective(model);
		return response;
	}
	
	/**
	 * 根据ID查找对象
	 * @param menuId
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/getById")
	@ResponseBody
	public MenuModel getById(Long menuId) throws Exception{
		MenuModel model = menuServiceClient.queryById(menuId);
		model.setChildrens(menuServiceClient.getOperateMenus(menuId));
		return model;
	}
	
	/**
	 * 删除数据
	 * @param userIds 主键列表
	 * @param response 
	 * @throws Exception
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public JsonResponse delete(Long[] menuIds) throws Exception{
		JsonResponse response = new JsonResponse(JsonResponse.SUCCESS,"删除成功");
		menuServiceClient.delete(menuIds);
		return response;
	}
	
	@RequestMapping("/queryMenuByApplicationId")
	@ResponseBody
	@Auth(verifyURL=false)
	public List<MenuModel> queryMenuByApplicationId(HttpServletRequest request){
		//从session中取出session值
		List<MenuModel> menuList = SessionUtils.getUserMenuList(request);
		return menuList;
	}
	
	/**
	 * 菜单树
	 * @param applicationId
	 * @return
	 */
	@RequestMapping("/menuTree")
	@ResponseBody
	@Auth(verifyURL=false)
	public List<EasyUiTree> menuTree(Long applicationId){
		List<MenuModel> menuList = menuServiceClient.queryMenuByApplicationId(applicationId);
		List<EasyUiTree> treeList = TreeUtil.menuModelListToEasyUiTree(menuList);
		List<EasyUiTree> result = new ArrayList<EasyUiTree>();
		EasyUiTree root = new EasyUiTree();
		root.setId(-1l);
		root.setText("菜单");
		root.setChildren(treeList);
		result.add(root);
		return result;
	}
	
	/**
	 * 菜单和操作树
	 * @param applicationId
	 * @return
	 */
	@RequestMapping("/menuAndOperateTree")
	@ResponseBody
	@Auth(verifyURL=false)
	public List<EasyUiTree> menuAndOperateTree(Long applicationId){
		List<MenuModel> menuList = menuServiceClient.queryMenuAndBtnByApplicationId(applicationId);
		List<EasyUiTree> treeList = TreeUtil.menuModelListToEasyUiTree(menuList);
		List<EasyUiTree> result = new ArrayList<EasyUiTree>();
		EasyUiTree root = new EasyUiTree();
		root.setId(-1l);
		root.setText("菜单");
		root.setChildren(treeList);
		result.add(root);
		return result;
	}
	
	/**
	 * 获取请求的菜单操作数据
	 * @param request
	 * @return
	 */
	public List<MenuModel> getReqOperateMenus(HttpServletRequest request,Long applicationId){
		UserModel user = SessionUtils.getUser(request);
		List<MenuModel> operateMenuList= new ArrayList<MenuModel>();
		String[] menuId  = request.getParameterValues("o_menuId");
		String[] menuName  = request.getParameterValues("o_menuName");
		String[] linkUrl  = request.getParameterValues("o_linkUrl");
		String[] deleted  = request.getParameterValues("o_deleted");
		if(menuId  == null || menuId.length < 1){
			return null;
		}
		for (int i = 0; i < menuId.length; i++) {
			if(StringUtils.isNotBlank(menuName[i]) && StringUtils.isNotBlank(linkUrl[i])){
				MenuModel operateMenu = new MenuModel();
				operateMenu.setMenuType(MenuTypeEnum.OPERATE.getType());
				operateMenu.setApplicationId(applicationId);
				operateMenu.setCreateUser(user.getUserName());
				operateMenu.setUpdateUser(user.getUserName());
				if(StringUtils.isNotBlank(menuId[i]) && NumberUtils.isNumber(menuId[i])){
					operateMenu.setMenuId(NumberUtils.toLong(menuId[i]));
				}
				operateMenu.setMenuName(menuName[i]);
				operateMenu.setLinkUrl(linkUrl[i]);
				operateMenu.setDeleted(deleted[i]);
				operateMenuList.add(operateMenu);
			}
		}
		return operateMenuList;
	}
	
	
}
